package com.example.util;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

/**
 * JWT用户工具类
 * 专门用于从JWT Token中获取用户信息
 */
@Slf4j
@Component
public class JwtUserUtil {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;
    
    /**
     * 从请求中提取Token
     */
    private String extractToken(HttpServletRequest request) {
        // 1. 从Authorization头中获取Bearer Token
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }

        // 2. 从自定义Token头中获取
        String tokenHeader = request.getHeader("Token");
        if (tokenHeader != null && !tokenHeader.isEmpty()) {
            return tokenHeader;
        }

        // 3. 从请求参数中获取（不推荐，仅用于测试）
        String tokenParam = request.getParameter("token");
        if (tokenParam != null && !tokenParam.isEmpty()) {
            return tokenParam;
        }

        return null;
    }

    /**
     * 从Authorization头中提取Token（推荐方式）
     */
    public String extractTokenFromAuthHeader(String authorizationHeader) {
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            return authorizationHeader.substring(7);
        }
        return null;
    }

    /**
     * 从Token头中提取Token
     */
    public String extractTokenFromTokenHeader(String tokenHeader) {
        if (tokenHeader != null && !tokenHeader.isEmpty()) {
            return tokenHeader;
        }
        return null;
    }
    
    /**
     * 获取当前请求的HttpServletRequest对象
     */
    private HttpServletRequest getCurrentRequest() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return attributes != null ? attributes.getRequest() : null;
        } catch (Exception e) {
            log.warn("获取当前请求失败", e);
            return null;
        }
    }
    
    /**
     * 从当前请求中获取用户信息
     */
    public User getCurrentUser() {
        HttpServletRequest request = getCurrentRequest();
        if (request == null) {
            return null;
        }
        return getUserFromRequest(request);
    }

    /**
     * 从当前请求上下文获取用户信息（推荐方式）
     */
    public User getCurrentUserFromContext() {
        try {
            HttpServletRequest request = getCurrentRequest();
            if (request == null) {
                return null;
            }

            // 优先从Authorization头获取
            String authHeader = request.getHeader("Authorization");
            User user = getUserFromAuthHeader(authHeader);
            if (user != null) {
                return user;
            }

            // 尝试从Token头获取
            String tokenHeader = request.getHeader("Token");
            return getUserFromTokenHeader(tokenHeader);
        } catch (Exception e) {
            log.warn("从当前请求上下文获取用户信息失败", e);
            return null;
        }
    }

    /**
     * 从当前请求上下文获取用户ID
     */
    public Long getCurrentUserIdFromContext() {
        User user = getCurrentUserFromContext();
        return user != null ? user.getId() : null;
    }

    /**
     * 从当前请求上下文获取用户名
     */
    public String getCurrentUsernameFromContext() {
        User user = getCurrentUserFromContext();
        return user != null ? user.getUsername() : null;
    }
    
    /**
     * 从指定请求中获取用户信息
     */
    public User getUserFromRequest(HttpServletRequest request) {
        try {
            String token = extractToken(request);
            if (token == null) {
                return null;
            }
            
            return getUserFromToken(token);
        } catch (Exception e) {
            log.warn("从请求中获取用户信息失败", e);
            return null;
        }
    }
    
    /**
     * 从Token中获取用户信息
     */
    public User getUserFromToken(String token) {
        try {
            // 验证token是否有效
            if (!jwtUtil.validateToken(token)) {
                return null;
            }

            // 从token中获取用户名
            String username = jwtUtil.getUsernameFromToken(token);
            if (username == null || username.isEmpty()) {
                return null;
            }

            // 根据用户名查询用户信息
            return userMapper.selectByUsername(username);
        } catch (Exception e) {
            log.warn("从Token中获取用户信息失败", e);
            return null;
        }
    }

    /**
     * 从Authorization头获取用户信息（推荐方式）
     */
    public User getUserFromAuthHeader(String authorizationHeader) {
        String token = extractTokenFromAuthHeader(authorizationHeader);
        if (token == null) {
            return null;
        }
        return getUserFromToken(token);
    }

    /**
     * 从Token头获取用户信息
     */
    public User getUserFromTokenHeader(String tokenHeader) {
        String token = extractTokenFromTokenHeader(tokenHeader);
        if (token == null) {
            return null;
        }
        return getUserFromToken(token);
    }

    /**
     * 从Authorization头获取用户ID
     */
    public Long getUserIdFromAuthHeader(String authorizationHeader) {
        User user = getUserFromAuthHeader(authorizationHeader);
        return user != null ? user.getId() : null;
    }

    /**
     * 从Token头获取用户ID
     */
    public Long getUserIdFromTokenHeader(String tokenHeader) {
        User user = getUserFromTokenHeader(tokenHeader);
        return user != null ? user.getId() : null;
    }

    /**
     * 从Authorization头获取用户名
     */
    public String getUsernameFromAuthHeader(String authorizationHeader) {
        User user = getUserFromAuthHeader(authorizationHeader);
        return user != null ? user.getUsername() : null;
    }

    /**
     * 从Token头获取用户名
     */
    public String getUsernameFromTokenHeader(String tokenHeader) {
        User user = getUserFromTokenHeader(tokenHeader);
        return user != null ? user.getUsername() : null;
    }
    
    /**
     * 获取当前用户ID
     */
    public Long getCurrentUserId() {
        User user = getCurrentUser();
        return user != null ? user.getId() : null;
    }
    
    /**
     * 获取当前用户名
     */
    public String getCurrentUsername() {
        User user = getCurrentUser();
        return user != null ? user.getUsername() : null;
    }
    
    /**
     * 获取当前用户昵称
     */
    public String getCurrentNickname() {
        User user = getCurrentUser();
        return user != null ? user.getNickname() : null;
    }
    
    /**
     * 检查当前用户是否已认证
     */
    public boolean isAuthenticated() {
        return getCurrentUser() != null;
    }
    
    /**
     * 检查当前用户是否为管理员
     */
    public boolean isAdmin() {
        User user = getCurrentUser();
        if (user == null) {
            return false;
        }
        
        // 这里可以根据实际业务逻辑判断是否为管理员
        // 例如：检查用户角色、权限等
        return "admin".equals(user.getUsername());
    }
    
    /**
     * 从请求中获取用户ID（兼容旧的实现方式）
     */
    public Long getUserIdFromRequest(HttpServletRequest request) {
        // 1. 优先从JWT Token中获取
        User user = getUserFromRequest(request);
        if (user != null) {
            return user.getId();
        }
        
        // 2. 兼容旧的方式：从请求头中获取用户ID（仅用于测试）
        String userIdStr = request.getHeader("User-Id");
        if (userIdStr != null && !userIdStr.isEmpty()) {
            try {
                return Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                log.warn("请求头中的User-Id格式不正确: {}", userIdStr);
            }
        }
        
        // 3. 从请求参数中获取（仅用于测试）
        String paramUserId = request.getParameter("currentUserId");
        if (paramUserId != null && !paramUserId.isEmpty()) {
            try {
                return Long.parseLong(paramUserId);
            } catch (NumberFormatException e) {
                log.warn("请求参数中的currentUserId格式不正确: {}", paramUserId);
            }
        }
        
        return null;
    }
    
    /**
     * 从请求中获取用户名（兼容旧的实现方式）
     */
    public String getUsernameFromRequest(HttpServletRequest request) {
        // 1. 优先从JWT Token中获取
        User user = getUserFromRequest(request);
        if (user != null) {
            return user.getUsername();
        }
        
        // 2. 兼容旧的方式：从请求头中获取用户名（仅用于测试）
        String username = request.getHeader("Username");
        if (username != null && !username.isEmpty()) {
            return username;
        }
        
        // 3. 从请求参数中获取（仅用于测试）
        String paramUsername = request.getParameter("currentUsername");
        if (paramUsername != null && !paramUsername.isEmpty()) {
            return paramUsername;
        }
        
        return null;
    }
}
